import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'dart:convert';
import 'model/group_model.dart';
import 'function.dart';
import 'package:flutter/services.dart';
import 'dart:async';
import "util/database.dart";

class ImportPage extends StatefulWidget {
  final Color mainColor;
  ImportPage(this.mainColor);
  @override
  _ImportPageState createState() => _ImportPageState();
}

class _ImportPageState extends State<ImportPage> {
  int success = 0;
  int exist = 0;
  int error = 0;
  String uid = "";
  List<GroupModel> groups;
  List<Map> devices = [];
  bool isImport = false;
  String importCode = "";
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initGroups();
    getStorage("uid").then((value) {
      this.uid = value;
    });
  }

  initBackupInfo() {}
  Future<bool> willPop() {
    Navigator.of(context).pop(isImport);
    return new Future.value(false);
  }

  import(List importDevices) async {
    if (importDevices.length == 0) {
      toast("未找到待导入设备");
      return;
    }

    showDialog<Null>(
      context: context,
      builder: (context) {
        return new AlertDialog(
          title: new Text("导入确认"),
          content: new Text("发现${importDevices.length}个账号，是否导入？"),
          actions: <Widget>[
            new FlatButton(
              onPressed: () {
                Navigator.of(context).pop();
                doImport(importDevices);
              },
              child: new Text(
                '导入',
              ),
            ),
            new FlatButton(
              onPressed: () async {
                Navigator.of(context).pop();
              },
              child: new Text(
                '取消',
              ),
            ),
          ],
        );
      },
    );
  }

  doImport(importDevices) async {
    WankeData table = new WankeData();
    await table.iniSqlite();
    if (table.db != null) {
      var batch = table.db.batch();
      for (var device in importDevices) {
        //判断账号是否存在
        var isExist = await findDeviceByAccount(device['phone']);
        if (isExist) {
          print("已存在");
          exist++;
        } else {
          Map<String, dynamic> data;
          data = {"group_id": 1, "account": device['phone'], "password": device['pwd'], "deviceid": rand(), "imeiid": rand(), "sessionid": rand(), "userid": rand(), "name": "获取中", "is_bind": "1"};
          batch.insert("devices", data);
        }
      }
      var res = await batch.commit();
      if (res != null) {
        success = res.length;
      } else {
        success = 0;
      }
    }
    if (success > 0) {
      isImport = true;
    }
    initGroups();
    showDialog<Null>(
      context: context,
      builder: (context) {
        return new AlertDialog(
          title: new Text("导入结果"),
          content: new Text("$success台设备导入成功\n$exist台设备已存在\n$error台设备导入失败"),
          actions: <Widget>[
            new FlatButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: new Text(
                '确定',
              ),
            ),
          ],
        );
      },
    );
  }

  initGroups() async {
    var existGroups = await getGroups();
    groups = existGroups.map((group) {
      return new GroupModel(id: group['id'], name: group['name'], devices: []);
    }).toList();
    initDevices();
  }

  initDevices() async {
    devices = [];
    var existDevices = await getDevices();
    if (existDevices != null) {
      existDevices.forEach((device) {
        var group_name;
        for (int i = 0; i < groups.length; i++) {
          if (groups[i].id == device['group_id']) {
            group_name = groups[i].name;
            break;
          }
        }
        devices.add({"phone": device['account'], "pwd": device['password'], "group": group_name});
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return new WillPopScope(
        child: Scaffold(
          appBar: new CupertinoNavigationBar(
            actionsForegroundColor: Colors.white,
            backgroundColor: widget.mainColor,
            border: new Border(bottom: BorderSide.none),
            middle: new Text(
              "导入导出",
              style: new TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.normal,
              ),
            ),
          ),
          body: new ListView(
            children: <Widget>[
              new ListTile(
                title: new Text("通过密文导入"),
                subtitle: new Text("导出账号密文后可以通过密文导入"),
                onTap: () async {
                  try {
                    var base64str = await Clipboard.getData("text/plain");
                    var utf8str = base64Decode(base64str.text);
                    var json = utf8.decode(utf8str);
                    List importDevices = jsonDecode(json);
                    await import(importDevices);
                  } catch (e) {
                    showDialog<Null>(
                      context: context,
                      builder: (context) {
                        return new AlertDialog(
                          title: new Text("导入失败"),
                          content: new Text("请先复制密文后再试"),
                          actions: <Widget>[
                            new FlatButton(
                              onPressed: () async {
                                Navigator.of(context).pop();
                              },
                              child: new Text(
                                '确定',
                              ),
                            ),
                          ],
                        );
                      },
                    );
                  }
                },
              ),
              new ListTile(
                title: new Text("批量输入账号"),
                subtitle: new Text("适合大量设备一次性添加"),
                onTap: () {
                  showDialog<Null>(
                    context: context,
                    builder: (context) {
                      return new AlertDialog(
                        title: new Text("开发中"),
                        content: new Text("敬请期待"),
                        actions: <Widget>[
                          new FlatButton(
                            onPressed: () async {
                              Navigator.of(context).pop();
                            },
                            child: new Text(
                              '确定',
                            ),
                          ),
                        ],
                      );
                    },
                  );
                },
              ),
              new ListTile(
                title: new Text("电脑联网导入"),
                subtitle: new Text("在电脑网页输入账号后导入到玩客随行"),
                onTap: () {
                  showDialog<Null>(
                    context: context,
                    builder: (context) {
                      return new AlertDialog(
                        title: new Text("请输入联网导入验证码"),
                        content: new TextField(
                          onChanged: (value) {
                            importCode = value;
                          },
                          style: new TextStyle(
                            fontSize: 15.0,
                            color: Colors.black,
                          ),
                          decoration: new InputDecoration(
                            hintText: "请输入联网导入验证码",
                            labelText: "验证码",
                            labelStyle: TextStyle(
                              fontWeight: FontWeight.w700,
                            ),
                          ),
                        ),
                        actions: <Widget>[
                          new FlatButton(
                            onPressed: () async {
                              var res = await getWebAccount(importCode);
                              Navigator.of(context).pop();
                              if (res['code'] == 0) {
                                toast(res['msg']);
                                return;
                              }
                              var base64str = res['msg'];
                              print(base64str);
                              var utf8str = base64Decode(base64str);
                              var json = utf8.decode(utf8str);
                              List importDevices = jsonDecode(json);
                              await import(importDevices);
                            },
                            child: new Text(
                              '导入',
                            ),
                          ),
                          new FlatButton(
                            onPressed: () {
                              importCode = "";
                              Navigator.of(context).pop();
                            },
                            child: new Text(
                              '取消',
                            ),
                          ),
                        ],
                      );
                    },
                  );
                },
              ),
              new ListTile(
                title: new Text("监控恢复"),
                subtitle: new Text("将开通监控的设备导入本地"),
                onTap: () async {
                  if (uid == null || uid == "") {
                    toast("登录后才可以从监控恢复");
                    return;
                  }
                  try {
                    var res = await getPushAccount(uid);
                    if (res['code'] == 0) {
                      toast(res['msg']);
                      return;
                    }
                    var base64str = res['msg'];
                    print(base64str);
                    var utf8str = base64Decode(base64str);
                    var json = utf8.decode(utf8str);
                    List importDevices = jsonDecode(json);
                    await import(importDevices);
                  } catch (e) {
                    print(e);
                    showDialog<Null>(
                      context: context,
                      builder: (context) {
                        return new AlertDialog(
                          title: new Text("导入失败"),
                          content: new Text("云备份数据有误"),
                          actions: <Widget>[
                            new FlatButton(
                              onPressed: () async {
                                Navigator.of(context).pop();
                              },
                              child: new Text(
                                '确定',
                              ),
                            ),
                          ],
                        );
                      },
                    );
                  }
                },
              ),
              new ListTile(
                title: new Text("云备份恢复"),
                subtitle: new Text("从玩客随行服务器恢复账号信息"),
                onTap: () async {
                  if (uid == null || uid == "") {
                    toast("登录后才可以从云备份恢复");
                    return;
                  }
                  try {
                    var saveResult = await getCloudBackup(uid);
                    print(saveResult);
                    if (saveResult['code'] == 0) {
                      toast(saveResult['msg']);
                      return;
                    }
                    var base64str = saveResult['msg'];
                    var utf8str = base64Decode(base64str);
                    var json = utf8.decode(utf8str);
                    List importDevices = jsonDecode(json);
                    await import(importDevices);
                  } catch (e) {
                    print(e);
                    showDialog<Null>(
                      context: context,
                      builder: (context) {
                        return new AlertDialog(
                          title: new Text("导入失败"),
                          content: new Text("云备份数据有误"),
                          actions: <Widget>[
                            new FlatButton(
                              onPressed: () async {
                                Navigator.of(context).pop();
                              },
                              child: new Text(
                                '确定',
                              ),
                            ),
                          ],
                        );
                      },
                    );
                  }
                },
              ),
              new Divider(),
              new ListTile(
                title: new Text("导出账号密文"),
                subtitle: new Text("导出账号密文后可以通过密文导入"),
                onTap: () {
                  if (devices.length == 0) {
                    toast("暂无账号，无法导出");
                    return;
                  }
                  var text = jsonEncode(devices);
                  var utf8str = utf8.encode(text);
                  var base64str = base64Encode(utf8str);
                  showDialog<Null>(
                    context: context,
                    builder: (context) {
                      return new AlertDialog(
                        title: new Text("导出账号密文"),
                        content: new Text("账号密文已生成，请妥善保存。"),
                        actions: <Widget>[
                          new FlatButton(
                            onPressed: () async {
                              Clipboard.setData(new ClipboardData(text: base64str));
                              toast("已复制");
                              Navigator.of(context).pop();
                            },
                            child: new Text(
                              '复制',
                            ),
                          ),
                          new FlatButton(
                            onPressed: () async {
                              Navigator.of(context).pop();
                            },
                            child: new Text(
                              '取消',
                            ),
                          ),
                        ],
                      );
                    },
                  );
                },
              ),
              new ListTile(
                title: new Text("导出账号明文"),
                subtitle: new Text("将账号信息通过明文方式导出"),
                onTap: () {
                  if (devices.length == 0) {
                    toast("暂无账号，无法导出");
                    return;
                  }
                  StringBuffer sb = new StringBuffer();
                  devices.forEach((device) {
                    sb.write(device['phone']);
                    sb.write("-");
                    sb.write(device['pwd']);
                    sb.write("\n");
                  });
                  showDialog<Null>(
                    context: context,
                    builder: (context) {
                      return new AlertDialog(
                        title: new Text("导出账号明文"),
                        content: new Text("账号明文文已生成，请妥善保存。"),
                        actions: <Widget>[
                          new FlatButton(
                            onPressed: () async {
                              Clipboard.setData(new ClipboardData(text: sb.toString()));
                              toast("已复制");
                              Navigator.of(context).pop();
                            },
                            child: new Text(
                              '复制',
                            ),
                          ),
                          new FlatButton(
                            onPressed: () async {
                              Navigator.of(context).pop();
                            },
                            child: new Text(
                              '取消',
                            ),
                          ),
                        ],
                      );
                    },
                  );
                },
              ),
              new ListTile(
                title: new Text("保存云备份"),
                subtitle: new Text("将账号信息保存到玩客随行服务器"),
                onTap: () async {
                  if (uid == null || uid == "") {
                    toast("登录后才可以保存到云备份");
                    return;
                  }
                  if (devices.length == 0) {
                    toast("暂无账号，无法导出");
                    return;
                  }
                  var text = jsonEncode(devices);
                  var utf8str = utf8.encode(text);
                  var base64str = base64Encode(utf8str);
                  var saveResult = await saveCloudBackup(uid, base64str);
                  toast(saveResult['msg']);
                },
              ),
            ],
          ),
        ),
        onWillPop: willPop);
  }
}
